package cn.tradewin.pmp.services.download.impl;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.tapestry5.services.Response;

import cn.tradewin.common.util.MimeSymbols;
import cn.tradewin.pmp.services.download.OutputStreamResponse;

public class PoiXlsOutputSreamResponse implements OutputStreamResponse {

	private final String filename;
	private final Workbook book;
	
	public PoiXlsOutputSreamResponse(Workbook book, String filename) {
		this.book = book;
		this.filename = filename;
	}
	
	
	@Override
	public String getContentType() {
		return MimeSymbols.APPLICATION_EXCEL;
	}

	@Override
	public void writeToStream(OutputStream out) throws IOException {
		book.write(out);		
	}

	@Override
	public void prepareResponse(Response response) {
		try {
			String output = new File(filename).getName();
			// 如果不设定该header的值，就会直接在浏览器上显示的内容。
			response.setHeader("Content-Disposition", "attachment; filename=\""  + URLEncoder.encode(output, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}